<template>
  <a-cascader
    v-model="internalValue"
    :options="options"
    :load-data="loadData"
    :change-on-select="false"
    :placeholder="placeholder"
    expand-trigger="click"
    style="width: 100%"
    :disabled="disabled"
    @change="handleChange"
  />
</template>

<script>
import { getAction } from '@/api/manage'

export default {
  name: 'DynamicCascader',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    apiConfig: {
      type: Object,
      required: true,
      validator: (value) => {
        return [
          'getFirstLevel',
          'getSecondLevel',
          'getThirdLevel',
          'getFourthLevel',
        ].every((key) => typeof value[key] === 'string')
      },
    },
    fieldNames: {
      type: Object,
      default: () => ({
        label: 'name',
        value: 'id',
        isLeaf: 'isLeaf',
      }),
    },
  },
  data() {
    return {
      internalValue: [],
      options: [],
      loadedNodes: new Map(), // 已加载的节点缓存
      loadingPath: false, // 路径加载状态
      pathQueue: [], // 路径加载队列
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(this.internalValue)) {
          this.internalValue = newVal
          if (newVal && newVal.length > 0) {
            this.loadPathForDisplay(newVal)
          } else {
            this.options = []
            this.loadInitialData()
          }
        }
      },
    },
  },
  mounted() {
    this.loadInitialData()
  },
  methods: {
    // 初始化加载第一级数据
    async loadInitialData() {
      try {
        const res = await getAction(this.apiConfig.getFirstLevel)
        this.options = this.formatData(res.result.data, 1)
        //this.loadedNodes.set('level_1', this.options)
      } catch (error) {
        console.error('加载初始数据失败:', error)
        this.$message.error('加载初始数据失败')
      }
    },

    // 动态加载数据
    async loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]

      // 如果正在加载或已经是叶子节点，则直接返回
      if (targetOption.loading || targetOption.isLeaf) return

      targetOption.loading = true

      try {
        const level = selectedOptions.length + 1
        const parentId = targetOption.value
        const cacheKey = `level_${level}_${parentId}`
        console.log('XXX')
        // 检查缓存
        // if (this.loadedNodes.has(cacheKey)) {
        //   targetOption.children = this.loadedNodes.get(cacheKey)
        //   return
        // }

        // 获取数据
        const children = await this.loadLevelData(parentId, level)
        console.log('获取数据>>>', children)
        // 更新数据
        targetOption.children = children
        targetOption.isLeaf = children.length === 0
        //this.loadedNodes.set(cacheKey, children)
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载下级数据失败')
      } finally {
        targetOption.loading = false
        this.$forceUpdate()
      }
    },

    // 为回显加载完整路径
    async loadPathForDisplay(valuePath) {
      if (this.loadingPath) {
        this.pathQueue.push(valuePath)
        return
      }

      this.loadingPath = true

      try {
        // 从第一级开始逐级加载
        for (let i = 0; i < valuePath.length; i++) {
          const currentValue = valuePath[i]
          const level = i + 1
          const parentValue = i > 0 ? valuePath[i - 1] : null

          // 检查当前节点是否已加载
          const nodeLoaded = this.isNodeLoaded(currentValue, level, parentValue)
          if (!nodeLoaded) {
            await this.ensureLevelLoaded(parentValue, level)
          }
        }

        // 确保最终值在选项中
        const lastValue = valuePath[valuePath.length - 1]
        if (!this.findOptionByValue(this.options, lastValue)) {
          console.warn('路径加载完成但未找到最终值:', lastValue)
        }
      } catch (error) {
        console.error('加载路径失败:', error)
      } finally {
        this.loadingPath = false
        // 处理队列中的下一个路径
        if (this.pathQueue.length > 0) {
          const nextPath = this.pathQueue.shift()
          this.loadPathForDisplay(nextPath)
        }
      }
    },

    // 加载指定层级数据
    async loadLevelData(parentValue, level) {
      const apiUrl = this.getApiUrlByLevel(level)
      const params = this.getRequestParams(parentValue, level)

      const res = await getAction(apiUrl, params)
      return this.formatData(res.result.data, level)
    },

    // 确保指定层级已加载
    async ensureLevelLoaded(parentValue, level) {
      const cacheKey = `level_${level}_${parentValue || 'root'}`

      // if (this.loadedNodes.has(cacheKey)) {
      //   return
      // }

      try {
        const data = await this.loadLevelData(parentValue, level)

        if (level === 1) {
          this.options = data
        } else {
          const parentOption = this.findOptionByValue(this.options, parentValue)
          if (parentOption) {
            this.$set(parentOption, 'children', data)
          }
        }

        //this.loadedNodes.set(cacheKey, data)
      } catch (error) {
        console.error(`确保层级${level}加载失败:`, error)
        throw error
      }
    },

    // 检查节点是否已加载
    isNodeLoaded(value, level, parentValue) {
      const cacheKey = `level_${level}_${parentValue || 'root'}`
      console.log(
        '!this.loadedNodes.has(cacheKey)>>',
        !this.loadedNodes.has(cacheKey)
      )
      //if (!this.loadedNodes.has(cacheKey)) return false

      const options =
        level === 1
          ? this.options
          : this.findOptionByValue(this.options, parentValue)?.children || []

      return options.some((opt) => opt.value === value)
    },

    // 根据value查找option
    findOptionByValue(options, value) {
      if (!options) return null

      // 广度优先搜索
      const queue = [...options]
      while (queue.length > 0) {
        const option = queue.shift()
        if (option.value === value) return option
        if (option.children) {
          queue.push(...option.children)
        }
      }
      return null
    },

    // 格式化数据
    formatData(data, level) {
      if (!data) return []
      return data.map((item) => ({
        label: item[this.fieldNames.label],
        value: item[this.fieldNames.value],
        isLeaf: level === 4 || item[this.fieldNames.isLeaf] || false,
        loading: false,
      }))
    },

    // 获取请求参数
    getRequestParams(parentId, level) {
      switch (level) {
        case 2:
          return { campusAreaId: parentId }
        case 3:
          return { buildingId: parentId }
        case 4:
          return { floorId: parentId }
        default:
          return {}
      }
    },

    // 根据层级获取API URL
    getApiUrlByLevel(level) {
      switch (level) {
        case 1:
          return this.apiConfig.getFirstLevel
        case 2:
          return this.apiConfig.getSecondLevel
        case 3:
          return this.apiConfig.getThirdLevel
        case 4:
          return this.apiConfig.getFourthLevel
        default:
          throw new Error('不支持的层级深度')
      }
    },

    // 值变化处理
    handleChange(value, selectedOptions) {
      this.internalValue = value
      this.$emit('input', value)
      this.$emit('change', value, selectedOptions)
      this.$emit('selectedValue', value)
      this.$emit('ok', value)
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>
